import { Col, Input, Modal } from "antd";
import SelectMenuTree from "./selectMenuTree";
import { ProForm } from "@ant-design/pro-components";
import { useEffect, useState } from "react";
import { ApartmentOutlined } from '@ant-design/icons';
import { findTreeById } from "@/utils";
import {
  listTree,
} from '@/api/appMenuResources/appMenuResources'
const SelectMenu = (props) => {
  const { id, value, onChange, wantRoot, placeholder, rootName, wrapId, onOk } = props;
  const [showValue, setShowValue] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedKeys, setSelectedKeys] = useState([value]);
  const [treeData, setTreeData] = useState();

  useEffect(() => {
    let nodeInfo = findTreeById(treeData || [], value)
    setShowValue(nodeInfo?.title)
  }, [treeData, value])

  useEffect(() => {
    listTree(wrapId || '0', 20).then((res) => {
      if (wantRoot) {
        setTreeData([
          {
            id: '-1',
            title: rootName || '根节点',
            children: res.data || [],
            attributes: {
              deptType: 'dept'
            }
          }
        ])
      } else {
        setTreeData(res.data || [])
      }
    })
  }, [])

  const triggerChange = (changedValue) => {
    onChange?.(changedValue);
  };
  const showSelectDept = () => {
    setIsModalOpen(true)
  };

  const handleOk = () => {
    triggerChange(selectedKeys[0])
    setIsModalOpen(false)
    onOk && onOk(selectedKeys[0], findTreeById(treeData || [], selectedKeys[0]))
  };
  const handleCancel = () => {
    setIsModalOpen(false)
  };


  const selectNode = (keys, info) => {
    setSelectedKeys(keys)
  }

  return (
    <>
      <Input
        id={id}
        value={showValue}
        readOnly
        onClick={showSelectDept}
        placeholder={placeholder}
        suffix={
          <ApartmentOutlined />
        }
      />
      <Modal title="菜单选择" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <SelectMenuTree id={wrapId} selectedKeys={selectedKeys} wantRoot={wantRoot} rootName={rootName} onSelect={selectNode} onTreeChange={setTreeData} />
      </Modal>
    </>
  );
};

const ProFormMenu = (props) => {
  let { colProps = {}, fieldProps = {}, placeholder, ...itemProps } = props
  return (
    <Col {...colProps}>
      <ProForm.Item {...itemProps}>
        <SelectMenu placeholder={placeholder} {...fieldProps} />
      </ProForm.Item>
    </Col>
  );
};

export default ProFormMenu;